<?php
/*
 * 缩略图编辑类
 * @package    sys
 * @author     Mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: 9e63c8f9c5be6021fceefa5ffa1a7cbd7233bd11 $
 */
defined('IN_IXDCW') or exit('Access Denied');
/**
 * 编辑器上传
 * Class EditorUpload
 */
class EditorUpload extends PictureUpload {

	/**
	 * 保存图片
	 */
	public function save($fileData) {
		global $DT;
		if (parent::save($fileData)) {
			// 检查是否文件超大. 压缩
			if (PhpThumbFactory::create($this->aimPath)->resize($DT['max_image'])->save($this->aimPath)) {
				$this->url = Picture::url($this->aimPath);
			}
			return true;
		} else {
			$this->setErr(self::ERR_NOT_WRITEABLE);
			return false;
		}
	}


	/**
	 * 对比并且删除不同的文件
	 * @param $new
	 * @param $old
	 * @param $userid
	 */
	public static function clearDiff($new, $old, $userid) {
		$new       = stripslashes($new);
		$diff_urls = $new_urls = $old_urls = array();
		$old_urls = self::getImgSrcs($old);
		$new_urls = self::getImgSrcs($new);

		// 需要删除的URL
		foreach ($old_urls as $url) {
			in_array($url, $new_urls) or $diff_urls[] = $url;
		}

		// 删除差异URL, 并且清掉url的session
		if ($diff_urls) {
			foreach ($diff_urls as $url) {
				self::deletePicture($url, $userid);
				self::clearPictureSession($url);
			}
		}
		if ($new_urls) {
			foreach ($new_urls as $url) {
				self::clearPictureSession($url);
			}
		}
		unset($new, $old, $matches, $url, $diff_urls, $new_urls, $old_urls);
	}

	/**
	 * 获取内容中不同的图片
	 * @param        $content
	 * @param string $ext
	 * @return array
	 */
	public function getImgSrcs($content, $ext = 'jpg|jpeg|gif|png|bmp|swf') {
		$urls = array();
		if (preg_match_all("/src=([\"|']?)([^ \"'>]+\.($ext))\\1/i", $content, $matches)) {
			foreach ($matches[2] as $url) {
				$urls[] = $url;
			}
		}
		return $urls;
	}

	public function error($append = '') {
		exit(json_encode(array('error' => $this->errno, 'message' => $this->error . $append)));
	}

	public function ok() {
		echo json_encode(array('error' => 0, 'url' => $this->url));
	}

}